package com.junqi.msg.event.listener;


import com.junqi.common.entity.Message;
import com.junqi.common.entity.RedisKeyManager;
import com.junqi.msg.adapter.WSAdapter;
import com.junqi.msg.event.UserOfflineEvent;
import com.junqi.msg.event.UserPushMsgEvent;
import com.junqi.msg.service.WebSocketService;
import com.junqi.msg.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 用户下线监听器
 *
 */
@Slf4j
@Component
class UserOfflineListener {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Async
    @EventListener(classes = UserOfflineEvent.class)
    public void pushMsg(UserOfflineEvent event) {
        String userId = event.getUserId();
        String roomId = event.getRoomId();

        //用户从房间缓存移除
        RedisUtil.setRemove(RedisKeyManager.generateKey(RedisKeyManager.ROOM_USERS,roomId),userId);

//        //组装用户上线消息，加入队列
//        Message message=new Message();
//        message.setId(RedisUtil.generateId(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG_ID,roomId)));
//        message.setSendTime(System.currentTimeMillis());
//        message.setUserName(userId);
//        message.setUserId(userId);
//        message.setRoomId(roomId);
//        message.setType(4);
//        message.setBody("用户下线");
//        //优先级低的消息
//        RedisUtil.zAdd(RedisKeyManager.generateKey(RedisKeyManager.ROOM_MSG,roomId,"02"),message,Double.valueOf(message.getSendTime()));
//
//        //有新消息入队，启动监听触发消息通知
//        applicationEventPublisher.publishEvent(new UserPushMsgEvent(this, roomId));
    }

}
